import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:bear_story/views.dart';
import '../main.dart';
import '../page/more.dart';
import '../page/login.dart';
import '../page/settings.dart';

class MineTabView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MineTabState();
  }
}

class _MineTabState extends State<MineTabView>
    with AutomaticKeepAliveClientMixin, HistoryBooksUpdateListener, CollectBooksListener {
  bool _dispose = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    addCollectBooksUpdateListener(this);
    addHistoryBooksUpdateListener(this);
    _dispose = false;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _dispose = true;
  }

  void updateLoginState() {
    if (getNowUser() == null) {
    } else {}
  }

  Widget _getImgWidget() {
    final user = getNowUser();
    if (user == null || user.headUrl == null || user.headUrl.length == 0) {
      return Container(
        width: 84,
        height: 84,
        child: GestureDetector(
          onTap: () {
            print("---click");
            if (getNowUser() == null) {
              pushPage2(context, LoginPage()).then((value) {
                setState(() {});
              });
            } else {
              pushPage(context, SettingsPage());
            }
          },
          child: ClipOval(
            child: Image.asset(
              "images/mrtx.png",
              fit: BoxFit.cover,
            ),
          ),
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(42)),
            border: Border.all(color: Color(0xffffc17f), width: 3)),
      );
    } else {
      return Container(
        width: 84,
        height: 84,
        child: GestureDetector(
          onTap: () {
            pushPage(context, SettingsPage());
          },
          child: ClipOval(
            child: Image.network(
              user.headUrl,
              fit: BoxFit.cover,
            ),
          ),
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(42)),
            border: Border.all(color: Color(0xffffc17f), width: 3)),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    print("_MineTabState----build");
    bool hasCollects = getNowUserCollects() != null && getNowUserCollects().length > 0;
    bool hasHistory = getHistoryList() != null && getHistoryList().length > 0;
    var devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
    // TODO: implement build
    return Builder(builder: (context){
      return Container(
        constraints: BoxConstraints.expand(),
        color: Colors.white,
        child: CustomScrollView(
          slivers: <Widget>[
            SliverList(
                delegate: SliverChildListDelegate([
                  Container(
                    constraints: BoxConstraints.expand(height: 150),
                    child: Stack(
                      children: <Widget>[
                        Container(
                          constraints: BoxConstraints.expand(),
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                                colors: [Color(0xFFff6e42), Color(0xfffb2b76)],
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter),
                          ),
                        ),
                        Center(
                          child: Container(
                            constraints: BoxConstraints.expand(height: 100),
                            padding: EdgeInsets.symmetric(horizontal: 15),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                _getImgWidget(),
                                Expanded(
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(horizontal: 14),
                                      child: Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Text(
                                            getNowUser() == null
                                                ? "点击登录"
                                                : getNowUser().nickName == null ? "" : getNowUser().nickName,
                                            maxLines: 1,
                                            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, color: Colors.white),
                                          ),
                                          Padding(padding: EdgeInsets.only(top: 10)),
                                          Text(
                                            getNowUser() == null ? "登录后可收听更多内容" : "${getNowUser().age}岁",
//                                      : "${getNowUser().age}岁/已学习${(getNowUser().learnTime / 60).toStringAsFixed(1)}分钟",
                                            maxLines: 1,
                                            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: Colors.white),
                                          )
                                        ],
                                      ),
                                    )),
//                              GestureDetector(
//                                onTap: () {},
//                                child: Container(
//                                  padding: EdgeInsets.all(5),
//                                  decoration: BoxDecoration(
//                                      borderRadius:
//                                      BorderRadius.all(Radius.circular(10)),
//                                      border: Border.all(color: Colors.white)),
//                                  child: Row(
//                                    children: <Widget>[
//                                      Icon(
//                                        Icons.share,
//                                        color: Colors.white,
//                                        size: 14,
//                                      ),
//                                      Text(
//                                        "分享",
//                                        style: TextStyle(
//                                            fontSize: 13,
//                                            color: Colors.white,
//                                            fontWeight: FontWeight.w300),
//                                      )
//                                    ],
//                                  ),
//                                ),
//                              )
                              ],
                            ),
                          ),
                        ),
                        Align(
                          alignment: FractionalOffset.bottomCenter,
                          child: Container(
                            constraints: BoxConstraints.expand(height: main_radius),
                            height: main_radius,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(main_radius), topRight: Radius.circular(main_radius))),
                          ),
                        )
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                        top: main_padding_top - main_radius, left: main_padding_left, right: main_padding_left),
                    child: TagView(
                      "我的收藏",
                      onTapMore: () {
                        if (getNowUser() != null) {
                          pushPage(context, MorePage("我的收藏", getNowUserCollects()));
                        }else{
                          showToast("暂无收藏记录", context);
                        }
                      },
                    ),
                  )
                ])),
            SliverList(
                delegate: SliverChildListDelegate([
                  Offstage(
                    offstage: hasCollects,
                    child: Container(
                      constraints: BoxConstraints.expand(height: 190),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image.asset(
                              "images/bear_d.png",
                              fit: BoxFit.none,
                            ),
                            Text(
                              "暂无收藏哦",
                              style: TextStyle(fontSize: 14, color: Color(0xff999999)),
                            )
                          ],
                        ),
                      ),
                    ),
                  )
                ])),
            SliverPadding(
              padding: EdgeInsets.only(top: main_padding_top, left: main_padding_left, right: main_padding_left),
              sliver: SliverGrid(
                  delegate: SliverChildBuilderDelegate(
                        (BuildContext context, int index) {
                      return Container(
                        child: BookAlbumView(
                          getNowUserCollects()[index],
                          centerTitle: true,
                        ),
                      );
                    },
                    childCount: hasCollects ? getNowUserCollects().length > 6 ? 6 : getNowUserCollects().length : 0,
                  ),
                  gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      mainAxisSpacing: main_padding_top,
                      crossAxisSpacing: main_padding_left,
                      childAspectRatio: getAlbumChildAspectRatio(devicePixelRatio, 3))),
            ),
            SliverList(
                delegate: SliverChildListDelegate([
                  Container(
                    color: background_color,
                    height: 8,
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                        top: main_padding_top - main_radius, left: main_padding_left, right: main_padding_left),
                    child: TagView(
                      "收听历史",
                      onTapMore: () {
                        if(getHistoryList()==null||getHistoryList().length==0){
                          showToast("暂无收听记录", context);
                        }else{
                          pushPage(context, MorePage("收听历史", getHistoryList()));
                        }

                      },
                    ),
                  )
                ])),
            SliverPadding(
              padding: EdgeInsets.only(top: main_padding_top, left: main_padding_left, right: main_padding_left),
              sliver: SliverGrid(
                  delegate: SliverChildBuilderDelegate(
                        (BuildContext context, int index) {
                      return Container(
                        child: BookAlbumView(
                          getHistoryList()[index],
                          centerTitle: true,
                        ),
                      );
                    },
                    childCount: getHistoryList().length > 6 ? 6 : getHistoryList().length,
                  ),
                  gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      mainAxisSpacing: main_padding_top,
                      crossAxisSpacing: main_padding_left,
                      childAspectRatio: getAlbumChildAspectRatio(devicePixelRatio, 3))),
            ),
            SliverList(
                delegate: SliverChildListDelegate([
                  Offstage(
                    offstage: hasHistory,
                    child: Container(
                      constraints: BoxConstraints.expand(height: 190),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image.asset(
                              "images/bear_d.png",
                              fit: BoxFit.none,
                            ),
                            Text(
                              "暂无收听记录哦",
                              style: TextStyle(fontSize: 14, color: Color(0xff999999)),
                            )
                          ],
                        ),
                      ),
                    ),
                  )
                ])),
            SliverPadding(padding: EdgeInsets.only(bottom: play_controller_bar_height))
          ],
        ),
      );
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void onHistoryBooksUpdate() {
    // TODO: implement onUpdate
    if (_dispose != null && !_dispose) {
      setState(() {});
    }
  }

  @override
  void onCollectBooksUpdate() {
    // TODO: implement onCollectBooksUpdate
    if (_dispose != null && !_dispose) {
      setState(() {});
    }
  }
}
